﻿using System;
using System.IO;
using UnityEngine;
using UnityEngine.Video;

namespace Yoozoo.Gta.Extension
{
    [RequireComponent(typeof(VideoPlayer))]
    public class VideoPlayerHelper : MonoBehaviour
    {
        public VideoPlayer VideoPlayer;

        public string VideoName;

        public bool useStreamingAsset;

        public void Awake()
        {
            VideoPlayer = GetComponent<VideoPlayer>();

            VideoPlayer.prepareCompleted += source =>
            {
                PrepareCompleted();
            };
            VideoPlayer.loopPointReached += source =>
            {
                LoopPointReached();
            };

            if (string.IsNullOrEmpty(VideoName))
            {
                if (VideoPlayer.clip == null)
                    return;
            }
            else if (useStreamingAsset)
            {
                if (Application.isEditor)
                {
                    var url = "file:///" + Path.Combine(Application.dataPath, "../Movie/" + VideoName);
                    VideoPlayer.url = url.Replace("\\", "/");
                }
                else
                {
                    if (Application.platform == RuntimePlatform.Android)
                        VideoPlayer.url = Path.Combine(Application.streamingAssetsPath, VideoName);
                    else
                        VideoPlayer.url = "file:///" + Path.Combine(Application.streamingAssetsPath, VideoName);
                }
            }
            else
            {
                VideoPlayer.clip = Resources.Load<VideoClip>(VideoName);
            }



            VideoPlayer.Prepare();
        }

        public void PrepareCompleted()
        {
            VideoPlayer.Play();
        }

        public void LoopPointReached()
        {
            VideoPlayer.Stop();
            gameObject.SetActive(false);
            onLoopPointReached?.Invoke();
        }

        private Action onLoopPointReached;

        public void SetLoopPointReached(Action action)
        {
            onLoopPointReached = action;
        }
    }
}
